package rge.orumus.encwallet;

import java.io.File;
import java.util.ArrayList;

import rge.orumus.androidutils.AndroidUtils;

import rge.orumus.encdb.EncDB;
import rge.orumus.encdb.FreeTextRecordData;
import rge.orumus.encdb.RecordHeader;
import rge.orumus.encdb.EncDB.RecordType;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;


public class EncWalletActivity extends Activity
	implements OnItemClickListener,
	OnClickListener
{
	
	private final static String debug_tag = "EncWallet";
	protected final static String APP_FOLDER = "/Android/data/rge.orumus.encwallet/files/";

	private String appFolder = "";
	private String EncDBName = "encdb.txt";
	EncDB encdb;
	
	
	ListView recordHeadersView = null;
	ArrayAdapter<String> recordHeadersAdapter = null;
	
	// Text Record view
	Button btnSaveTextRecord =  null;
	EditText edHeader = null;
	EditText edText = null;
	int currentIndex = -1;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
		Log.v(debug_tag, "EncWallet started");
		
		super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
		// check if external storage is present and available for writing
		if(!AndroidUtils.isExternalStorageWritable())
		{
			// MessageBox(R.string.msg_Error, R.string.msg_ExtStorageNotWritable);
			finish();
			return;
		}
		
		appFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_FOLDER;
		
		// check if data folder exists and create if necessary
		File data_folder = new File(appFolder);
		if(!AndroidUtils.ensureFolderExists(data_folder)){
			// MessageBox(R.string.msg_Error, R.string.msg_CannotCreateFolder);
			finish();
			return;
		}
		
		switchToMainView();
    }
    
    private void switchToMainView() {
        setContentView(R.layout.main);
		recordHeadersView = (ListView) findViewById(R.id.recordlist);
		recordHeadersAdapter = new ArrayAdapter<String>(this, R.layout.recordheader);
		recordHeadersView.setAdapter(recordHeadersAdapter);
		recordHeadersView.setOnItemClickListener(this);
		
        encdb = new EncDB(this, appFolder + EncDBName);
        ArrayList<RecordHeader> rh = encdb.GetHeaders();
        
		for(int i = 0; i < rh.size(); i++){
			recordHeadersAdapter.add(rh.get(i).ToHmiString());
		}
	}

	private void switchToTextRecordView() {
        setContentView(R.layout.textrecord);
        btnSaveTextRecord = (Button) findViewById(R.id.btnSaveTextRecord);
    	edHeader = (EditText) findViewById(R.id.edHeader);
    	edText = (EditText) findViewById(R.id.edText);
        btnSaveTextRecord.setOnClickListener(this);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.appmenu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.quit:
                quitApp();
                return true;
            case R.id.about:
                showAboutDialog();
                return true;
            case R.id.find:
                showFindDialog();
                return true;
            case R.id.new_card:
                addNewCardRecord();
                return true;
            case R.id.new_image:
                addNewImageRecord();
                return true;
            case R.id.new_online_credentials:
                addNewOnlineCredentialsRecord();
                return true;
            case R.id.new_text:
                addNewTextRecord();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    public void onClick(View v){
    	if(v == btnSaveTextRecord){
            saveTextRecord();
    		switchToMainView();
    	}
    		
    }

	private void saveTextRecord() {
		String title = edHeader.getText().toString();
		String text = edText.getText().toString();
		RecordHeader rh = new RecordHeader(currentIndex, RecordType.RECORD_TEXT, title);
		FreeTextRecordData ftrd = new FreeTextRecordData(text);
		encdb.updateRecord(rh, ftrd);
	}

	private void addNewTextRecord() {
		switchToTextRecordView();
		currentIndex = -1;
		edHeader.setText("");
    	edText.setText("");
	}

	private void addNewOnlineCredentialsRecord() {
		// TODO Auto-generated method stub
		messageBox(R.string.msg_Informatrion, R.string.msg_Not_implemented);
	}

	private void addNewImageRecord() {
		// TODO Auto-generated method stub
		messageBox(R.string.msg_Informatrion, R.string.msg_Not_implemented);
	}

	private void addNewCardRecord() {
		// TODO Auto-generated method stub
		messageBox(R.string.msg_Informatrion, R.string.msg_Not_implemented);
	}

	private void showFindDialog() {
		// TODO Auto-generated method stub
		messageBox(R.string.msg_Informatrion, R.string.msg_Not_implemented);
	}

	private void showAboutDialog() {
		// TODO Auto-generated method stub
		messageBox(R.string.msg_Informatrion, R.string.msg_Not_implemented);
	}

	private void quitApp() {
		finish();
	}

    private void messageBox(int title, int text){
    	String strTitle = getString(title);
    	String strText = getString(text);
    	messageBox(strTitle, strText);
    }

    private void messageBox(String title, String text){
	    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	    alertDialog.setTitle(title);
	    alertDialog.setMessage(text);
	    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
	       public void onClick(DialogInterface dialog, int which) {
	       }
	    });
	    // TODO: alertDialog.setIcon(R.drawable.icon);
	    alertDialog.show();
    }

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		String title = "" + id;
		String text = recordHeadersAdapter.getItem(position).toString();
		messageBox(title, text);
	}
}